//  Created by 莫瑞权 on 2022/6/13.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit
 public class TFInteractLive: TF_1vN_LiveMain,TF1to16VideoAreaDelegate,UITextFieldDelegate,TFWhiteboardToolsDelegate,TFSetButtonViewDelegate,TFFullViewDelegate,TFMarqueeDelegate,TalkfunSDKLiveDelegate,TalkfunSDKRtcDelegate  {

    let videoArea = TF1to16VideoArea()
    var threeFrame = CGRectZero
    let cameraView = TFCameraViewManager()
    let videoFullScreen = UIButton()
    let tipsView = TFTipsView()//模式切换
    var chatDisable:Bool = false
    let drawing = TF1to16Drawing()//画板
    var fullScreen:Bool = false
    var cameraViewFrame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    let inviteAlert = UIAlertController()
     
     public static func showVC(vc: UIViewController, token: String, userID: String){
         let  tovc = TFInteractLive()
         tovc.access_token = token
         tovc.userID = userID
         tovc.modalPresentationStyle = .fullScreen
         tovc.hidesBottomBarWhenPushed = true
         self.TF_current().present(tovc, animated: true)
     }
     public override func viewDidLoad() {
        super.viewDidLoad()
         print("进入直播=========")
        //6是大班互动模式
        self.modetype = "6"
        //0：非小班
        //1：双人，
        //2：1V6 模式，
        //3：1V16模式
        self.smallType = "3"
        
        self.fullView.delegate = self
        
        
        //TODO: 视频区域
        self.addvideoArea()
        //TODO: 画板
        self.addDrawing()
     
       //TODO: 未上讲台播放旁路的视频view
       self.cameraView.isHidden = false
        //改
        let videoViewH:CGFloat = 108.0
        let videoViewW = 144.0
       self.cameraView.frame = CGRect(x: self.superView.frame.size.width-videoViewW, y: 28, width: videoViewW, height: videoViewH)
         
       self.cameraView.backgroundColor = UIColor.black
        //双击手势
        self.cameraView.doubleClickGesture(target: self, action: #selector(doubleTapActionClick))
         threeFrame = CGRect(x: self.superView.frame.width - 144, y: 0, width:144, height: self.superView.frame.size.height)
//        self.threeArea = UIView(frame: CGRect(x: self.superView.frame.width - 144 - 26, y: 0, width:144 + 26, height: self.superView.frame.size.height));
//        self.view.addSubview(self.threeArea)
      
        

        //TODO: 网络错误
         self.superView.addSubview(self.cameraView)
         self.addTallkFenPromptTool()
         self.superView.addSubview(self.promptTool)
        //TODO: 自己的奖杯
        self.addAwardView()
        self.superView.addSubview(self.keyboardTool)
       //TODO: 聊天列表
        self.addChatList()
        //TODO: 投票列表
        self.addVotingArea()
        //TODO: 回答
        self.qskQuestions()
        //TODO:  键盘
        self.addKeyboardArea()
         
       
        //TODO:跑马灯
        self.marquee.delegate = self
        self.superView.addSubview(self.marquee)
        self.marquee.frame = CGRect(x: 0, y: 40, width: self.superView.frame.size.width, height: 32)
        if (self.marquee.frame.size.width != self.marquee.view.frame.size.width) {
            self.marquee.refreshData()
         }
        self.addpopupPutView()
        //TODO: 1.添加导航栏
        self.navigationBarTools1to16()
        //TODO:状态切换
        self.tipsView.isHidden = true
        self.tipsView.frame = self.superView.bounds
        self.view.addSubview(self.tipsView)
        //TODO:初始化小班SDK
        let talkfunSDK = self.inittalkfunSDK(self.access_token, courseType: TalkfunCourseTypeInteractiveLive)
        talkfunSDK.delegate = self
        //小班的代理
        talkfunSDK.rtcManager.delegate = self
        //配置sdk
        self.configureSDK()
//         self.setButtonView.hiddenBtn(true)
    }
    // 大班互动的视频的配置  宽高
    public func videoProfileWidth(_ width: CGFloat, hight: CGFloat) {
        //手机160
        var cameraViewWidth:CGFloat  = 144
        var cameraViewHeight:CGFloat = 108
 
        if (width/hight == 16.0/9.0) {
            cameraViewWidth   = 144
            cameraViewHeight  = 108

        }
        //计算出比例
        let videoAreaWidth:CGFloat  = self.superView.frame.size.width
        self.cameraView.frame = CGRect(x: self.superView.frame.width-cameraViewWidth - 13, y: 28, width: cameraViewWidth, height: cameraViewHeight)
//        self.threeArea.backgroundColor = UIColor.black
    }

  @objc func doubleTapActionClick()
    {
            if (self.fullScreen==false) {

                self.fullScreen = true

                self.cameraViewFrame = self.cameraView.frame
                UIView.animate(withDuration: 0.5) {
           
                self.cameraView.frame = self.superView.bounds

                }

            }else{
                self.fullScreen = false

                UIView.animate(withDuration: 0.5) {
                    self.cameraView.frame = self.cameraViewFrame
                }

            }
      
    }

    @objc func switchButton(_ btn:UIButton)
    {
        self.talkfunSDK.exchangePPTAndCameraContainer()

        if (self.talkfunSDK.isExchanged) {
             self.drawing.defaultDrawing1vN.isHidden = true
            self.cameraView.defaultDrawing1vN.isHidden = false
           if (self.talkfunSDK.isLoadCourseware == false&&self.talkfunSDK.realDesktop ) {
                  self.drawing.defaultDrawing1vN.isHidden = false
               self.cameraView.defaultDrawing1vN.isHidden = true
            }
            btn.setImage(UIImage.init(named: "HTLive.bundle/smallPpt"), for: .normal)
            
           }else{
               self.cameraView.defaultDrawing1vN.isHidden = true
               if(self.talkfunSDK.isLoadCourseware == false){
                   if (self.talkfunSDK.realDesktop) {
                       self.drawing.defaultDrawing1vN.isHidden = true
                       self.cameraView.defaultDrawing1vN.isHidden = false
                   }else{
                       self.drawing.defaultDrawing1vN.isHidden = false
                       self.cameraView.defaultDrawing1vN.isHidden = true
                   }
               }
               btn.setImage(UIImage.init(named: "HTLive.bundle/bigPpt"), for: .normal)
            
           }
    }
    @objc func navigationBarTools1to16()
     {

         self.superView.addSubview(self.navigationBar)
         self.navigationBar.frame = self.superView.bounds
         self.navigationBar.addTopViewAndBottomView()
         self.navigationBar.setButton.isHidden = true
         self.navigationBar.isFullButton.isHidden = false
         self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType: self.smallType, shipinType: "0")
       
         self.navigationBar.backgroundColor = UIColor.clear

         //TODO:返回
         self.navigationBar.backButtonAddTarget(self, action: #selector(btnClick))
         //TODO:设置
         self.navigationBar.setButtonTools.addTarget(self, action: #selector(setButtonToolsClick), for: .touchUpInside)
         //TODO:全屏
         self.navigationBar.isFullButton.addTarget(self, action: #selector(isFullButtonClicck), for: .touchUpInside)
        
         self.navigationBar.title.text = ""
         self.navigationBar.time.isHidden = true

         //TODO:刷新
         self.navigationBar.refresh.addTarget(self, action: #selector(refresh), for: .touchUpInside)
    
         //TODO:设置线路
         self.navigationBar.setButton.addTarget(self, action: #selector(setButtonClick), for: .touchUpInside)
       
         //TODO:切换摄像头与ppt
         self.navigationBar.switchButton.addTarget(self, action: #selector(switchButton), for: .touchUpInside)

          //TODO: iphone 聊天列表显示隐藏 事件
         self.navigationBar.chat.addTarget(self, action: #selector(cahtButtonClick), for: .touchUpInside)
         
         //TODO:启动聊天输入栏
         self.navigationBar.inputFieldButton.addTarget(self, action: #selector(inputFieldButtonClick), for: .touchUpInside)
         //TODO:申请上讲台
         self.navigationBar.ondium.addTarget(self, action: #selector(PodiumClick), for: .touchUpInside)
         //TODO:提问列表
         self.navigationBar.askQuestions.addTarget(self, action: #selector(askQuestionsClick), for: .touchUpInside)
         //TODO:投票列表
         self.navigationBar.voteBtn.addTarget(self, action: #selector(questionButtonClick), for: .touchUpInside)
         //TODO:课件下载
         self.navigationBar.courseDownBtn.addTarget(self, action: #selector(courseDownBtnClick), for: .touchUpInside)
         
//

     }
     
     @objc func isFullButtonClicck(_ btn:UIButton)
     {
         btn.isSelected = !btn.isSelected
         if btn.isSelected{
             for i in 0...self.navigationBar.buttonArray.count - 1{
                 if i != 0 &&
                        i != (self.navigationBar.buttonArray.count - 1){
                     print(i)
                     let index = self.navigationBar.buttonArray[i]
                     let view = self.navigationBar.bottomStackView.arrangedSubviews[index]
                     view.isHidden = true
                 }
             }
             
             threeFrame.size.width = 144.0
             var threeWidth = 144.0
             var toolFrame = promptTool.frame
             toolFrame.size.width = CGRectGetWidth(self.superView.frame) - threeWidth
             promptTool.frame = toolFrame
             
             //drawing
             
             var drawFrame = drawing.frame
             drawFrame.size.width = CGRectGetWidth(self.superView.frame) - threeWidth
             drawing.frame = drawFrame
             
             //cameraView
             var cameraFrame = self.cameraView.frame
             cameraFrame.origin.y = 0
             cameraFrame.origin.x = CGRectGetWidth(self.superView.frame) - threeWidth
             self.cameraView.frame = cameraFrame
             
             //下面的功能按钮
             let viewsWidth = 100.0
             self.navigationBar.isFullButton.isHidden = false
             var stackFrame = self.navigationBar.bottomStackView.frame
             stackFrame.size.width = viewsWidth
             stackFrame.origin.x = self.superView.frame.size.width - threeWidth - viewsWidth - 30
             self.navigationBar.bottomStackView.frame = stackFrame
             //发言
             var inputFrame = self.navigationBar.inputField.frame
             inputFrame.size.width = threeWidth
             inputFrame.origin.x = CGRectGetMinX(threeFrame)
             self.navigationBar.inputField.frame = inputFrame
             self.navigationBar.inputFieldButton.frame = self.navigationBar.inputField.bounds
             
             self.chatArea.tableView.reloadData()
         }else{
             //            UIView.animate(withDuration: 0.5) {
             for i in 0...self.navigationBar.buttonArray.count - 1{
                 let index = self.navigationBar.buttonArray[i]
                 let view = self.navigationBar.bottomStackView.arrangedSubviews[index]
                 view.isHidden = false
             }
             
             var toolFrame = promptTool.frame
             toolFrame.size.width = CGRectGetWidth(self.superView.frame)
             promptTool.frame = toolFrame
             
             var drawFrame = drawing.frame
             drawFrame.size.width = CGRectGetWidth(self.superView.frame)
             drawing.frame = drawFrame
             
             var cameraFrame = self.cameraView.frame
             cameraFrame.origin.y = 28
             cameraFrame.origin.x = CGRectGetWidth(self.superView.frame) - 144 - 13.0
             self.cameraView.frame = cameraFrame
             
             threeFrame.size.width = 0
             self.tipsView.frame = self.superView.frame;
             let totalWidth = CGFloat(self.navigationBar.buttonArray.count * 36)
             var viewsWidth = totalWidth + CGFloat((self.navigationBar.buttonArray.count - 1) * 20)
             var frame = self.navigationBar.bottomStackView.frame
             frame.size.width = CGFloat(viewsWidth)
             frame.origin.x = self.superView.frame.size.width - 30 - CGFloat(viewsWidth)
             
             self.navigationBar.bottomStackView.frame = frame
             self.navigationBar.inputField.frame =  CGRect(x: 25, y: self.navigationBar.bottomView.frame.size.height - 8 - 36, width: CGRectGetWidth(self.navigationBar.bottomView.frame) - CGFloat(viewsWidth) - 100, height: 36)
             //            }
             
         }
         threeChatViewShow(isThree: btn.isSelected,isShowChat: false)
         self.cameraView.isUserInteractionEnabled = !btn.isSelected
//         self.liveBackgroundImageV.frame = self.promptTool.frame
     }
    //刷新
    @objc func refresh()
    {
        if(self.talkfunSDK.isRefresh==false){
            self.navigationBar.switchButton.setImage(UIImage.init(named: "HTLive.bundle/bigPpt"), for: .normal)
            
            //先隐藏音视频
            self.drawing.mediaContainerView.playStatus(TalkfunMultiMediaStatusChangeListenerClose, time: 0)
         
            self.promptTool.loading.isHidden = false
            self.videoArea.videoSessionsArray.removeAllObjects()

            self.talkfunSDK.reload()

        }

    }
    //2.视频区域
    func addvideoArea()
     {
         let videoAreaHeight:CGFloat = self.videoH()
         let videoAreaWidth:CGFloat  = self.superView.frame.size.width
         let videoAreaY:CGFloat = 0.0
 
         let videoAreaX:CGFloat = 0

        self.videoArea.isHidden = true
        
        self.videoArea.delegate = self
        self.videoArea.frame = CGRect(x: videoAreaX, y: videoAreaY, width: videoAreaWidth, height: videoAreaHeight)
        self.videoArea.backgroundColor = UIColor(red: 19/255.0, green: 21/255.0 , blue: 25/255.0, alpha: 1)
         self.superView.addSubview(self.videoArea)

    }
    
   @objc func cahtButtonClick()
    {
        self.isShowTopViewAndBottomView(false)
        if (self.drawPower && self.talkfunSDK.liveStatus == TalkfunLiveStatusStart) {
            self.drawing.whiteboardTools.isHidden = false
        } else {
            self.drawing.whiteboardTools.isHidden = true
        }
        self.isShowVotingArea(false)
//        self.showChatArea(true)
        self.threeChatViewShow(isThree: self.navigationBar.isFullButton.isSelected, isShowChat: true)
        self.navigationBar.chat.clearRedDot()
    }
    
    func threeChatViewShow(isThree:Bool, isShowChat:Bool)
     {
         
         if (self.drawPower && self.talkfunSDK.liveStatus == TalkfunLiveStatusStart) {
             self.drawing.whiteboardTools.isHidden = false
         } else {
             self.drawing.whiteboardTools.isHidden = true
         }
         self.isShowVotingArea(false)
         self.navigationBar.chat.clearRedDot()
         
         let  ChatAreaY:CGFloat = 0.0
         let  ChatAreaHeight:CGFloat = self.superView.frame.size.height
         let  ChatAreaW:CGFloat = 335
         let  ChatAreaX:CGFloat = self.superView.frame.size.width
         
         if (isThree) {
             self.chatArea.frame = CGRect(x: CGRectGetMinX(threeFrame), y: CGRectGetMaxY(self.cameraView.frame), width: CGRectGetWidth(threeFrame), height:CGRectGetHeight(threeFrame) -  CGRectGetHeight(self.cameraView.frame) - CGRectGetMinY(self.navigationBar.bottomStackView.frame) + 30.0)

         }else{
//             self.chatArea.frame = CGRect(x: ChatAreaX, y: ChatAreaY, width: ChatAreaW, height: ChatAreaHeight)
             self.showChatArea(isShowChat)

         }
     }

    func lineButtonClick()
    {
        self.talkfunSDK.rtcManager.whiteboard.drawType = self.drawType
    }

    func eraserButtonClick()
    {
        self.drawing.whiteboardTools.isHidden = true
        self.drawType = self.talkfunSDK.rtcManager.whiteboard.drawType
        self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeBoxDelete

    }
    @objc func PodiumClick(_ btn:UIButton)

    {
    
        //未申请
        if (self.talkfunSDK.rtcManager.applyStatus == .noApply) {
            

            let  alerts = self.showContent("是否申请连麦?", Message: "", Cancel: "取消", Sure: "确定")
        
            alerts.resultIndex = { [weak self] () in
                
                guard let `self` = self else { return }
       

                //申请上讲台

                self.talkfunSDK.rtcManager.apply {[weak self] code, error in
                    
                    guard let `self` = self else { return }
                    
                        if (code == 0) {

                            self.TF_toast("你已申请连麦")
                            
                            self.navigationBar.ondium.onPodium(.applying)
                            self.drawing.podiumConfiguration.podiumStatus(.applying)
                             
                        }else {
                            self.TF_toast(error!.msg)
                        
                        }

                    alerts.removeFromSuperview()
         
                }


            }

         //已经申请上讲台
        }else if (self.talkfunSDK.rtcManager.applyStatus == .applying) {

            let  alerts = self.showContent("是否取消申请连麦?", Message: "", Cancel: "取消", Sure: "确定")
    

            alerts.resultIndex = { [weak self] () in
                
                guard let `self` = self else { return }

                alerts.removeFromSuperview()

                    //老师已经让自己上讲台
                if ( self.talkfunSDK.rtcManager.applyStatus == .allow) {
                        return
                    }
                    //取消申请
                self.talkfunSDK.rtcManager.cancel {[weak self] code, error in
                    
                    guard let `self` = self else { return }
               
                        if (code == 0) {

                            self.TF_toast("你已取消申请连麦")

                            self.drawing.podiumConfiguration.podiumStatus(.noApply)
                            self.navigationBar.ondium.onPodium(.noApply)
                         
                        }

                }


            }
        //讲台上
        }else if (self.talkfunSDK.rtcManager.applyStatus == .allow) {
            let  alerts = self.showContent("是否取消连麦?", Message: "", Cancel: "取消", Sure: "确定")
            
            //点击事件
            alerts.resultIndex = { [weak self] () in
                
                guard let `self` = self else { return }
                alerts.removeFromSuperview()
               

                //申请下讲台
                self.talkfunSDK.rtcManager.downRTC {[weak self] code, error in
                    
                    guard let `self` = self else { return }
                 
                        if (code == 0) {

                               //1.不是1v6  2.已经是连麦了
                               if(self.smallType != "2" && self.talkfunSDK.rtcManager.allowApply == false){

                                   self.drawing.podiumConfiguration.onPodium.isHidden = true

                                }
                                if (self.modetype == "6"){
                                self.isShowvCameraView(true)
                                    self.videoArea.videoSessionsArray.removeAllObjects()
                            }

                            self.TF_toast("你已取消申请连麦")

                            self.videoArea.removeFromVideo(self.talkfunSDK.rtcManager.getUserModel())

                            self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: self.smallType, shipinType: "0")

                             

                            self.navigationBar.ondium.onPodium(.noApply)

                                self.drawing.whiteboardTools.isHidden = true


                        }else {
                            self.TF_toast(error!.msg)
                      

                        }

                }


            };


        }

    }
    func setMicroPhoneDeviceStatusUI(_ open:Bool)
    {
        
        if (open) {
            self.talkfunSDK.rtcManager.setMicroPhoneDeviceStatus(true) {[weak self] code, error, model in
                guard let `self` = self else { return }
                if(code==0)
                {
                    self.TF_toast("你的麦克风已开启")

                    self.videoArea.updateModel(model)

                    self.navigationBar.updateModel(model)
                }else {
            
                    self.TF_toast(error.msg)
                }
            }
        }else
        {
            self.talkfunSDK.rtcManager.setMicroPhoneDeviceStatus(false) {[weak self] code, error, model in
                guard let `self` = self else { return }
                
                if(code==0)
                {
                    self.TF_toast("你的麦克风已关闭")
                    self.videoArea.updateModel(model)


                    self.navigationBar.updateModel(model)
                }else {
                    self.TF_toast(error.msg)
                }

            }
        }

    }
    //5.画板
    func addDrawing()
    {
        self.drawing.whiteboardTools.delegate = self
//        self.drawing.backgroundColor = self.superView.backgroundColor
        self.drawing.responderView.responderButton.addTarget(self, action: #selector(responderButtonClick), for: .touchUpInside)
        self.superView.addSubview(self.drawing)

        let drawingX:CGFloat = 0
        var drawingY = self.videoArea.frame.maxY
        let  drawingW = self.superView.frame.size.width


        if (self.modetype == "6")
        {
            drawingY = 0
        }
        let drawingH:CGFloat = self.superView.frame.size.height-drawingY
        
        self.drawing.frame = CGRect(x: drawingX, y: drawingY, width: drawingW, height: drawingH)
     
        self.drawing.tempFrame = self.drawing.frame
        
        self.drawing.doubleTapActionBlock = { [weak self]  in
            guard let `self` = self else { return }

            if (self.talkfunSDK.rtcManager.applyStatus != .allow) {

                if (self.drawing.frame.size.height == self.superView.frame.size.height&&self.modetype=="6") {
                    return
                }
            }
          // 回到主线程更新UI
  
            UIView.animate(withDuration: 0.5) {
                         self.isShowqskQuestionsView(false)
//                        self.showChatArea(false)
                self.threeChatViewShow(isThree: self.navigationBar.isFullButton.isSelected, isShowChat: false)

                       self.isShowVotingArea(false)
                    if ( self.drawing.frame.size.height != self.superView.frame.size.height) {
                        self.navigationBar.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/shrink1vN"), for: .normal)
                        
                    
                        self.drawing.frame = self.superView.bounds
                        
                        self.drawing.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/ppt_narrow"), for: .normal)
                     
                    }else{
                        self.drawing.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/ppt_enlarge"), for: .normal)
                        self.navigationBar.isFullButton.setImage(UIImage.init(named: "HTLive.bundle/fullScreen1vN"), for: .normal)
                       
                         self.drawing.frame =  self.drawing.tempFrame

                    }

            }

        }

        self.drawing.whiteboardDidTouchedBlock = { [weak self]  in
            guard let `self` = self else { return }
            self.touchesBeganUI()
        }

    }
    func touchesBeganUI()
    {
        self.isShowOtherArea(false)
        self.isShowSetButtonToolsArea(false)

        if (self.navigationBar.topView.frame.origin.y==0) {
            if !self.navigationBar.isFullButton.isSelected {
                self.isShowTopViewAndBottomView(false)
            }
           
          
        }else{
        
            self.isShowTopViewAndBottomView(true)
        }
//        if !self.navigationBar.fullButton.isSelected{
//            self.showChatArea(false)
//        }
        self.threeChatViewShow(isThree: self.navigationBar.isFullButton.isSelected, isShowChat: false)
        self.isShowVotingArea(false)
        self.isShowqskQuestionsView(false)
    }
  //  #pragma mark 配置SDK
    func configureSDK()
    {
       
        
        self.talkfunSDK.configureCameraContainerView(self.cameraView)
        self.talkfunSDK.configurePPTContainerView(self.drawing.view)
       // 配置桌面分享容器
        self.talkfunSDK.configureDesktopContainerView(self.drawing.desktopContainerView)
       // 配置桌面音视频容器
        self.talkfunSDK.configureMediaContainerView(self.drawing.mediaContainerView.playVIew)
    }

  //  #pragma 代理画板当前页的frame
    public func whiteboardPageFrame(_ frame: CGRect) {

        self.drawing.isFullButton.frame = CGRect(x: frame.origin.x + frame.size.width-5-33, y: frame.origin.y + frame.size.height-5-33, width: 33, height: 33)

        self.drawing.mediaContainerView.pageFrame = frame

        self.updatePlayVIewFrame()

    }
    func updatePlayVIewFrame()
    {
        if (self.drawing.mediaContainerView.pageFrame.size.width>0&&self.drawing.mediaContainerView.docType != 0 ) {
               //音频
             if (self.drawing.mediaContainerView.docType==5) {
                 self.drawing.mediaContainerView.playVIew.frame =  self.drawing.mediaContainerView.pageFrame;


             }else if (self.drawing.mediaContainerView.docType==4) {
              //视频
                 var playVIewWidth = self.drawing.bounds.size.height/(9.0/16.0);
                 if (playVIewWidth>self.drawing.bounds.size.width) {
                     playVIewWidth = self.drawing.bounds.size.width
                 }

                 self.drawing.mediaContainerView.playVIew.frame = CGRect(x: (self.drawing.frame.size.width - playVIewWidth)/2, y: 0, width: playVIewWidth, height: self.drawing.bounds.size.height)



             }

        }

    }

   // #pragma mark 退出
    @objc func btnClick()
    {
        let alert = self.showContent("你确定要退出直播间吗?", Message: "", Cancel: "取消", Sure: "确定")

        alert.resultIndex = { [weak self] () in
            alert.removeFromSuperview()
            guard let `self` = self else { return }

            if (self.talkfunSDK.rtcManager.applyStatus == .allow) {

                self.talkfunSDK.leaveliveroom(self.access_token) { [weak self]  (code, error) in
                    guard let `self` = self else { return }
                    if (code == 0) {

                        self.exit()
                     
                    }

                }

              } else {
                  self.exit()
                

          }
           

          }

      }
    func exit()
    {
        self.UIInterfaceOrientationPortrait()
        self.drawing.mediaContainerView.removeObserver()

        self.marquee.destroy()
       
        NotificationCenter.default.removeObserver(self)
        self.qa_sendTimer?.invalidate()
        self.qa_sendTimer = nil
        self.chat_sendTimer?.invalidate()
        self.chat_sendTimer = nil
        self.awardView.animationDidStop()

        self.promptTool.destroy()
        self.talkfunSDK.destroy()
        self.navigationBar.destroy()
 
        //返回上一页
        self.TF_dismissUI()


    }

    /**
     设置开关 tag
     0.摄像头,
     1.前置,
     2.镜像,
     3.美颜,
     4.麦克风,
     5.扬声器,
     6.弹幕

     */
    //#pragma mark 设置用户开关
    
    public func SetUserFunction(_ tag: NSInteger, andSwitch: UISwitch) {
        let isopen = andSwitch.isOn
        if (tag == 0)
        {
            //摄像头开关
            if(self.videoFrequentlyClick == true){
                self.TF_toast("点击太快啦，稍等一下再试试吧")
           
                return
            }
            self.videoFrequentlyClick = true;

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.0) {
                self.videoFrequentlyClick = false
            }
           

            let closeVideoState = TalkfunSettingToolsManager.shared().getVideoStatus(self.talkfunSDK.xid)
            
            
             if (closeVideoState) {
                 
                 self.TF_toast("主播关闭了你的摄像头")
                 return;
             }

            if (self.talkfunSDK.rtcManager.applyStatus == .allow) {
                self.talkfunSDK.closeVideoBeforeOnPodium = false
                
                
                self.talkfunSDK.rtcManager.setCameraDeviceStatus(!isopen) {[weak self] (code , error, model) in
                    guard let `self` = self else { return }
            
                        if (code==0) {
                            self.videoArea.updateModel(model)

                            self.setButtonView.hiddenBtn(!isopen)

                            self.navigationBar.updateModel(model)
                        }else
                        {
                            self.TF_toast(error.msg)
                        }

                }

            }
             else {
                self.talkfunSDK.closeVideoBeforeOnPodium = true
            }
            
            andSwitch.isOn = !isopen
            TalkfunSettingToolsManager.shared().setToolsSwitchVideo(!isopen, xid: self.talkfunSDK.xid)
        }
    
        else  if (tag == 1) {
            //前置/后置
            andSwitch.isOn = !isopen
            self.setButtonView.upDataLanguage()

            self.talkfunSDK.rtcManager.switchCamera()

            TalkfunSettingToolsManager.shared().setToolsSwitchCamera(!isopen, xid: self.talkfunSDK.xid)


        } else if (tag == 2) {
            //镜像开关
            self.talkfunSDK.rtcManager.setLocalViewMirror(isopen)
            TalkfunSettingToolsManager.shared().setToolsSwitchMirror(!isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 3) {
            //美颜开关
            self.talkfunSDK.rtcManager.setBeautyEffectOptions(isopen)

            TalkfunSettingToolsManager.shared().setToolsSwitchBeauty(isopen, xid: self.talkfunSDK.xid)


        } else if (tag == 4) {
            //麦克风开关
            if(self.audioFrequentlyClick == true){
                self.TF_toast("点击太快啦，稍等一下再试试吧")
                return
            }
            self.audioFrequentlyClick = true

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                self.audioFrequentlyClick = false
            }


            let closeAudioState = TalkfunSettingToolsManager.shared().getAudioStatus(self.talkfunSDK.xid)

             if (closeAudioState) {
                 self.TF_toast("主播关闭了你的麦克风")

                 return;
             }


            if (self.talkfunSDK.rtcManager.applyStatus == .allow) {
                self.talkfunSDK.closeAudioBeforeOnPodium = false

                self.setMicroPhoneDeviceStatusUI(!isopen)
          
            } else {
                self.talkfunSDK.closeAudioBeforeOnPodium = true
            }
            TalkfunSettingToolsManager.shared().setToolsSwitchAudio(!isopen, xid: self.talkfunSDK.xid)

            andSwitch.isOn = !isopen
        } else if (tag == 5) {
            //扬声器开关
            self.talkfunSDK.rtcManager.muteAllRemoteAudio(!isopen)
            TalkfunSettingToolsManager.shared().setToolsSwitchSpeaker(isopen, xid: self.talkfunSDK.xid)

        } else if (tag == 6) {
            //弹幕开关
            andSwitch.isOn = !isopen
         
            TalkfunSettingToolsManager.shared().setToolsSwitchBarrage(!isopen, xid: self.talkfunSDK.xid)
            if andSwitch.isOn  {
                
            }else
            {
                self.barrageRender.bulletSwitch = false

            }
            self.barrageRender.bulletSwitch = andSwitch.isOn
        }else if (tag == 7) {
            //中英文切换

            if (andSwitch.isOn == false) {
                  //调用 系统设置配置语言
                TFChangeLanguage.sharedInstance.setLanguage(language: "en")

            } else {
                TFChangeLanguage.sharedInstance.setLanguage(language: "zh-Hans")

            }
            andSwitch.isOn = !andSwitch.isOn

            //sdk 保存
            TalkfunSettingToolsManager.shared().setToolsLanguageChange(andSwitch.isOn, xid: self.talkfunSDK.xid)

            self.updataLanguage(isopen)

        }
    }

    //#pragma mark 中英文切换
    func updataLanguage(_ isyes:Bool)

    {
        self.setButtonView.upDataLanguage()
        self.navigationBar.upDataLanguage()
        self.keyboardTool.layoutSubviews()

        //更换语言
        self.qskQuestionsView.upDataLanguage()
        self.chatArea.upDataLanguage()
        self.signInView.upaDataLanguage()
        self.drawing.timerView.upDataLanguage()
        self.drawing.responderView.upDataLanguage()
        self.navigationBar.ondium.upDataLanguage(isyes)

        self.votingArea.voteDetail.upDataLanguage()
        self.votingArea.upDataLanguage()
        self.drawing.listOfWinners.updateLanguage()
        self.scoreView.updateLanage()
        self.chatArea.tableView.reloadData()
    }

    /**
     * @param status 播放状态
     * @param time   播放时间
     */
    public func multiMediaApplicate(_ status: TalkfunMultiMediaStatusChangeListener, time: Int32) {

        self.drawing.mediaContainerView.playStatus(status ,time:NSInteger(time))
        ////关闭
        if (status == TalkfunMultiMediaStatusChangeListenerClose) {
            //是否应用了
            self.drawing.mediaContainerView.isMediaApplicatea = false
            if (self.navigationBar.topView.frame.origin.y == 0 && self.talkfunSDK.rtcManager.whiteboard.graffiti) {
                self.drawing.whiteboardTools.isHidden = false
            }
        }else if (status != TalkfunMultiMediaStatusChangeListenerError) {
            //是否应用了
            self.drawing.mediaContainerView.isMediaApplicatea = true
        }


    }

    /* 应用
     *@param id 素材id
     * @param docType  5：音频 ，4：视频
     * @param title 素材标题
     * @param duration 视频时长
     */
    public func multiMediaApplicate(_ ID: String, docType type: Int32, title: String, duration: Int32) {


        if (type==0) {
            self.drawing.isFullButton.isHidden = true
        }
        self.drawing.mediaContainerView.docType(Int(type), duration: Int(duration))
     

        if (self.drawing.mediaContainerView.docType==4) {
            self.drawing.whiteboardTools.isHidden = true
        }
        self.drawing.mediaContainerView.isMediaApplicatea = true
        self.updatePlayVIewFrame()
    }
   // #pragma mark  定时器倒计时的代理
    /* 定时器开始倒计时
    *@param total 总时长
    * @param duration 剩余的时长倒计
    */
    public func timerStartWidthTotal(_ total: Int, duration: Int) {
        self.drawing.timerView.isHidden = false
        self.drawing.timerView.timerStartWidthTotal(total,duration:duration)

    }
    /*
    // 定时器暂停
    // @param duration 剩余的时长倒计
    */
    public func timerPause(_ duration: Int) {
        self.drawing.timerView.timerPause(duration)
    }
    /* 结束定时器
     */
    public func timerClose() {
        self.drawing.timerView.isHidden = true
    }
    /*
     定时器重新开始
    */
    public func timerReReady() {
        self.drawing.timerView.endTimeLaer()
    }
    /*
      定时器倒计时完成
    */
    public func timerEnd() {
        self.drawing.timerView.endTimeLaer()
    }

  //  #pragma mark 开始抢答
    @objc func responderButtonClick()
    {
        self.talkfunSDK.sendResponder {[weak self] (code, error) in
            guard let `self` = self else { return }
            if(code==0)
            {
                self.drawing.responderView.isHidden = true
            }
        }

    }
   // #pragma mark   抢答器的代理

    // 应用抢答器
    public func responderApplicate(_ dict: [AnyHashable : Any]) {
        self.drawing.responderView.isHidden = false
        self.drawing.responderView.backgroundView1.isHidden = false
        self.drawing.responderView.backgroundView2.isHidden = true
    }
    /*
       抢答器开始共用了多少秒
    */

    public func responderStartWidthDuration(_ duration: Int) {
        self.drawing.responderView.responderStartWidthDuration(duration)
    }

    /*
       抢答器关闭
    */
    public func responderClose() {
        self.drawing.responderView.isHidden = true
    }

    /*
      定时器归0
    * @param duration 剩余的时长倒计
    */
    public func responderReReady() {
        self.drawing.responderView.responderStartWidthDuration(0)
    }

    /* 抢答器结束
    */
    public func responderEnd() {

        self.drawing.responderView.isHidden = false
        self.drawing.responderView.backgroundView1.isHidden = false
        self.drawing.responderView.backgroundView2.isHidden = true

        self.drawing.responderView.timeLabel.text = "00:00"

        self.drawing.responderView.noOne()
    }
    /* 抢答器成功的学员名字
     */
    public func responderSecond(_ name: String, second duration: Int, isMe: Bool) {


        if (isMe==false) {
            //失败
            self.drawing.responderView.fail(name, xid: self.talkfunSDK.xid)

        }else{
            //成功name
            self.drawing.responderView.setResponder(name, duration: duration, xid: self.talkfunSDK.xid)

        }

    }
    //#pragma mark  转盘的代理
    //转盘应用
    public func turntableApplicate() {
        self.drawing.turntableView.turntableApplicate()
    }

    /* 转盘应用
       selected 选中的号码
       frequency 转盘未关闭前共转了多少次
    */
    public func turntableSelected(_ selected: Int, frequency count: Int) {

        self.drawing.turntableView.startRotationAnimation(CGFloat(selected))
    }
    //转盘关闭
    public func turntableClose() {
        self.drawing.turntableView.closeButtonClict()
    }
    
    
    //   #pragma mark双击视频view  代理
    public func objectDidDragged(_ vc: TF1to16VideoAreaCell) {
           self.double_tap_to_full_screenUI(vc.model!)
       }

   // TFFullViewDelegate  全屏缩小的代理
     public func objectFullViewDidDragged(_ vc:TFFullView)
    {
        self.talkfunSDK.scalingMode = .fill
        vc.model.isFull = false

        self.fullView.isHidden = true
        self.fullView.removeFromSuperview()
     
            for i in 0..<vc.model.view.subviews.count {

               let subView = vc.model.view.subviews[i] as UIView
                subView.frame = vc.bounds
            }
        


        self.videoArea.isFull = false
        self.videoArea.collectionView!.reloadData()

    }


    public func dealSingleTap(_ vc: TF1to16VideoAreaCell) {
        
    }

    /**
     * @画板载入课件
     */
    public func loadCourseware() {
        
        self.drawing.defaultDrawing1vN.isHidden = true
    }
    /**
    *当前是不是桌面模式
    */
    
    public func isRealDesktop(_ isDesktop: Bool) {
 
        if (isDesktop) {
            self.drawing.whiteboardTools.isHidden = true

            self.drawing.defaultDrawing1vN.isHidden = true

            self.cameraView.isHidden = true
        }else{
            if (self.talkfunSDK.isLoadCourseware == false) {
                self.drawing.defaultDrawing1vN.isHidden = false
            }

            if (self.talkfunSDK.rtcManager.whiteboard.graffiti) {
                if (self.drawing.mediaContainerView.docType != 4 ) {
                    self.drawing.whiteboardTools.isHidden = false
                }

            }
            self.cameraView.defaultDrawing1vN.isHidden = true
        }


    }
    @objc func setButtonClick()
    {
   
        self.talkfunSDK.getLineList { [weak self] result in
            guard let `self` = self else { return }
            if (result!.code==0 ) {

                self.other.addRouteList(result!.data)

                self.isShowOtherArea(true)
            }
        }

    }

    func isShowvCameraView(_ isShow:Bool)
    {
        let drawingX:CGFloat = 0
        
        var drawingY = self.videoArea.frame.maxY

        let drawingW = self.superView.frame.size.width

        if (isShow )
        {
            drawingY = 0
        }
         let drawingH = self.superView.frame.size.height - drawingY

        if (isShow&&self.talkfunSDK.realDesktop == false) {
            self.cameraView.isHidden = false

            self.videoArea.isHidden = true
        }else{

            self.cameraView.isHidden = true
            self.videoArea.isHidden = false

        }

        self.drawing.frame = CGRect(x: drawingX, y: drawingY, width: drawingW, height: drawingH)
       
        //大班互动才动态变
        if (self.modetype == "6") {
           self.drawing.tempFrame =  self.drawing.frame
        }

    }

  //  #pragma mark TODO:初始化SDK-----------------
    
    public func onEnterRoom(_ code: Int, result error: TFError) {
        print(self.talkfunSDK.roomInfo.liveMode)
        
        if (self.setButtonView.frame.width==0) {
            self.setButtonView.initUI(frame: CGRect(x: self.superView.frame.size.width+220, y: 0, width: self.superView.frame.size.width, height: self.superView.frame.size.height), xid: self.talkfunSDK.xid)
           

        self.setButtonView.xid = self.talkfunSDK.xid
        self.setButtonView.delegate2 = self
        self.setButtonView.contentSize = CGSize(width: 0, height: 400)
 
        self.superView.addSubview(self.setButtonView)

        }
        

        if ( code == 0 ) {
            
        self.barrageRender.bulletSwitch = TalkfunSettingToolsManager.shared().getToolsSwitchBarrage(self.talkfunSDK.xid)

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {

           
                self.isShow = true
            }



            self.promptTool.loading.isHidden = true
            
            
            let isOn = TalkfunSettingToolsManager.shared().getToolsLanguageChange(self.talkfunSDK.xid)


             if (isOn) {
                 
                 TFChangeLanguage.sharedInstance.setLanguage(language: "en")
                
                 self.updataLanguage(isOn)
             }

            self.navigationBar.title.text = self.talkfunSDK.roomInfo.title

            if (self.drawing.turntableView.isClose) {
                self.drawing.turntableView.isHidden = false
            }

            self.drawing.podiumConfiguration.podiumStatus(self.talkfunSDK.rtcManager.applyStatus)

            //获取提问列表
            self.getAListOfQuestions()

            //可用于投票判断是不是自己
            self.votingArea.voteDetail.uid = self.talkfunSDK.uid;
            self.chatArea.uid = self.talkfunSDK.uid;
            //只有显示的时候才请求课件数据  课件下载开关
            self.onDocumentDownload(self.talkfunSDK.roomInfo.mod_document_download_live.enable)
           

        }else{
       
//            self.TF_toast(error.msg)
        }

    }
    //#pragma mark 未连麦人员打开涂鸦权限
    public func onMemberDrawEnable(_ model: TFMember) {

        self.drawPower = true
        if (model.isMe) {
            self.TF_toast("你已被授予涂鸦权限")
      
            self.drawing.whiteboardTools.isHidden = false
        }else
        {
            if (self.drawing.whiteboardTools.isHidden == false) {
                self.TF_toast("你的涂鸦权限已被收回")
             
                self.drawing.whiteboardTools.isHidden = true
            }
        }
    }
    //#pragma mark 未连麦人员关闭涂鸦权限
    public func onMemberDrawDisable(_ model: TFMember) {

        self.drawPower = false
        if (model.isMe) {
            self.TF_toast("你的涂鸦权限已被收回")
        
            self.drawing.whiteboardTools.isHidden = true
        }
    }
  //  #pragma mark true :单体禁言  false:单体解除禁言
    public func onChatDisable(_ state: Bool) {

        if (state) {
             self.chatDisable = true
            self.TF_toast("你已被禁言")
            
              self.navigationBar.inputField.isHidden = true;

        }else{
             self.chatDisable = false
            self.TF_toast("禁言已解除")
       
             self.navigationBar.inputField.isHidden = false
            self.chatArea.chatIsDisable(false)

        }
    }
   // #pragma mark true :全体禁言 false:全体解除禁言
    public func onChatDisableAll(_ state: Bool) {
 
        if(state==true){
            self.TF_toast("你已被禁言")
          
            self.navigationBar.inputField.isHidden = true

            //能说话
        }else if(state == false){
        if (self.chatDisable == false) {
            if (self.navigationBar.inputField.isHidden) {
                self.TF_toast("禁言已解除")
              
            }

            self.navigationBar.inputField.isHidden = false
            }
        }
    }
 //   #pragma mark 当前用户被踢出房间的事件回调
    // #pragma mark  被踢出房间
    public func onMemberKick() {

         let alert = UIAlertController.init(title: "", message: "你被退出房间了", preferredStyle:.alert)
      
         let otherAction:UIAlertAction = UIAlertAction.init(title: "退出", style: .default) { action in
             self.exit()
         }
         alert.addAction(otherAction)
         if  UIDevice.current.model.hasPrefix("iPad") {
             alert.popoverPresentationController?.sourceView = self.superView
             alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
         }
         
         self.present(alert, animated: true)
     }
  //  #pragma mark  直播间状态
    public func onLiveStatus(_ status: TalkfunLiveStatus)
    {
        if (status == TalkfunLiveStatusWait)
        {
            self.promptTool.loading.isHidden = true
            self.drawPower = false
            self.promptTool.backgroundImage.imageView.isHidden = true
            self.promptTool.backgroundImage.label.isHidden = false
            
            self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")
            
            self.promptTool.backgroundImage.label.text = "请稍等，直播马上开始~"
            let width = CGRectGetWidth(self.promptTool.backgroundImage.frame)
            let height = CGRectGetHeight(self.promptTool.backgroundImage.frame)
            self.promptTool.backgroundImage.label.frame = CGRect(x: 0, y:(height - 22.5) / 2, width: width, height: 22.5)
            self.videoArea.isHidden = true
//            self.navigationBar.isFullButton.isHidden = false
//            self.navigationBar.buttonArray.append(self.navigationBar.bottomStackView.arrangedSubviews.count - 1)
//            let count = (self.navigationBar.buttonArray.count + 1)
//            let viewsWidth = (CGFloat(count) * 50.0) - 30.0
//            self.navigationBar.bottomStackView.frame = CGRect(x: CGRectGetWidth(self.navigationBar.bottomView.frame) - viewsWidth, y: self.navigationBar.bottomView.frame.size.height - 8 - 36, width: viewsWidth, height: 36)
//            self.navigationBar.inputField.frame =  CGRect(x: 25, y: self.navigationBar.bottomView.frame.size.height - 8 - 36, width: CGRectGetWidth(self.navigationBar.bottomView.frame) - viewsWidth - 70, height: 36)
            self.isFullButtonClicck(self.navigationBar.isFullButton)
        }
       else if (status == TalkfunLiveStatusStart)

        {
            self.drawing.view.isHidden = false;
            self.cameraView.defaultDrawing1vN.isHidden = true
            self.promptTool.backgroundImage.backgroundColor = UIColor.clear
            self.scoreView.successBtton()
//           self.navigationBar.isFullButton.isHidden = false
//           self.navigationBar.buttonArray.append(self.navigationBar.bottomStackView.arrangedSubviews.count - 1)
            self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType:  self.smallType, shipinType: "0")
           
        
            if (self.modetype == "6" && self.talkfunSDK.realDesktop == false)
            {
                self.cameraView.isHidden = false
                self.isShowvCameraView(true)
            }

           self.navigationBar.barrage.setImage(UIImage.init(named: "HTLive.bundle/barrage1vN"), for: .normal)
         
            self.navigationBar.barrage.tag = 1

            if (self.talkfunSDK.isLoadCourseware == false && self.talkfunSDK.realDesktop == false) {
                self.drawing.defaultDrawing1vN.isHidden = false
            }
            self.videoArea.isHidden = false

            self.navigationBar.setButton.isHidden = false
            self.navigationBar.setButtonTools.isHidden = false

            self.navigationBar.title.text = self.talkfunSDK.roomInfo.title

            self.promptTool.loading.isHidden = true

            self.promptTool.backgroundImage.isHidden = true
           
        }else{
            self.drawing.view.isHidden = true

            if(self.talkfunSDK.evaluate && self.modetype == "6" &&  self.isScore == false){

                       //配置
                self.scoreView.setScoreConfig(self.talkfunSDK.roomInfo.scoreConfig.valueList)
                   //1.启动了评分
                   self.isScore = true
                       //TODO:评分提交
                
                self.scoreView.submit.addTarget(self, action: #selector(submitClick), for: .touchUpInside)
                 
                   //2.添加了评分
                self.superView.addSubview(self.scoreView)

           }
            self.objectFullViewDidDragged(self.fullView)
        
            self.navigationBar.takeThePodium(false, liveStart: false, modetype: self.modetype, smallType:  self.smallType, shipinType: "0")
            
            self.isShowvCameraView(false)
    
            self.cameraView.isHidden = false
            self.drawing.whiteboardTools.isHidden = true
            self.navigationBar.barrage.tag = 0
            self.drawing.podiumConfiguration.isHidden = true
            self.navigationBar.barrage.setImage(UIImage.init(named: "HTLive.bundle/barrageOff1vN"), for: .normal)


            self.drawing.defaultDrawing1vN.isHidden = true
            self.videoArea.isHidden = true
            self.navigationBar.setButton.isHidden = true
            self.drawing.isFullButton.isHidden = true
            self.navigationBar.setButtonTools.isHidden = false
            
            self.drawing.podiumConfiguration.podiumStatus(.noApply)
            self.navigationBar.ondium.onPodium(.noApply)
            self.promptTool.backgroundImage.isHidden = false
            self.promptTool.loading.isHidden = true
            self.promptTool.backgroundImage.isHidden = false
            self.promptTool.backgroundImage.backgroundColor =  UIColor.clear
            self.promptTool.backgroundImage.imageView.isHidden = false
            self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/livestoped")
            
            self.promptTool.backgroundImage.label.text = "直播已结束"
            self.promptTool.backgroundImage.label.isHidden = false
            self.navigationBar.time.isHidden = true
            self.navigationBar.title.text = ""
            self.videoArea.liveStop()

            self.talkfunSDK.rtcManager.whiteboard.setLineRgbColor(UIColor(red: 0.99, green: 0.18, blue: 0.02, alpha: 1))
        
            //申请上讲台   隐藏
            self.drawing.podiumConfiguration.onPodium.isHidden = true
            self.navigationBar.setButtonTools.isHidden = true
            self.keyboardWillHide1()
         

            self.drawing.mediaContainerView.isMediaApplicatea = false

        }

    }

    //#pragma mark 直播间模式切换
    public func onLiveModeChange(status:TFLiveModeChange)
    {
            //当模式
        let mode:TalkfunLiveMode = status.currentMode
        //rtc模式
        if mode == TalkfunLiveModeRTC  {
            self.tipsView.title.text = "正在进入连麦模式，请稍等..."
        }else if(mode == TalkfunLiveModeVideo)
        {
            self.tipsView.title.text = "正在进入观看模式，请稍等..."
         
            if (self.talkfunSDK.realDesktop == false) {
            self.cameraView.isHidden = false
            }
        }else if(mode == TalkfunLiveModeDesktop)
        {
            self.tipsView.title.text = "正在进入桌面模式，请稍等..."
            self.cameraView.isHidden = true

        }

        self.tipsView.isHidden = false
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            self.tipsView.isHidden = true;
        }

    }
  //  #pragma mark  视频播放状态改变  -黑屏加菊花时用到
    
    public func playerLoadStateDidChange(_ loadState: TalkfunPlayerLoadState) {
 
        if (loadState == TalkfunPlayerLoadState.stalled) {
      //            NSLog(@"发生卡顿，显示菊花");
            self.cameraView.activityIndicator.startAnimating()

        }else  {
             //    NSLog(@"正常播放，移除菊花");
            self.cameraView.activityIndicator.stopAnimating()
        }
        
    }
   // #pragma mark  ------------------RTC 模式-----------------------
  //  #pragma mark 讲台开启
    public func rtcOpen() {

        if(self.talkfunSDK.rtcManager.applyStatus == .noApply && self.smallType != "2"){
            self.TF_toast("连麦功能已开启")
          
        }
        self.navigationBar.ondium.onPodium(.noApply)
        self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: self.smallType, shipinType: "0")

    }
    //#pragma mark 讲台关闭
    public func rtcClose() {

        self.rtcInvitecancel()
     
        self.drawing.podiumConfiguration.podiumStatus(.noApply)
        self.TF_toast("连麦功能已关闭")

        //所有学生下讲台
        self.videoArea.allTheStudentsWalkedOffThePodium()

        self.drawing.podiumConfiguration.onPodium.isHidden = true

        self.drawing.whiteboardTools.isHidden = true
        self.navigationBar.takeThePodium(false, liveStart: true, modetype: self.modetype, smallType: self.smallType, shipinType: "0")
         
        if (self.modetype == "6")
        {
          if (self.talkfunSDK.realDesktop == false) {
           self.cameraView.isHidden = false
         }
            self.isShowvCameraView(true)
        }

    }

   // #pragma mark 允许上讲台
    public func rtcUp(_ model: TalkfunRtcModel) {
 
        if(model.isMe){
            self.navigationBar.switchButton.setImage(UIImage.init(named: "HTLive.bundle/bigPpt"), for: .normal)
        
        if (self.talkfunSDK.isLoadCourseware == false) {
            self.drawing.defaultDrawing1vN.isHidden = false
        }
            self.isShowOtherArea(false)
        self.navigationBar.isOndium = true
            self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: self.smallType, shipinType: "0")
        
        self.navigationBar.ondium.onPodium(.allow)

        if (self.modetype == "6")
        {
        if (self.talkfunSDK.realDesktop == false) {
        self.cameraView.isHidden = true
        }
            self.isShowvCameraView(false)
        }

            self.drawing.podiumConfiguration.podiumStatus(.allow)

            self.navigationBar.updateModel(model)

        }
        self.videoArea.updateModel(model)
    }
   // #pragma mark 拒绝用户上讲台
    public func rtcRejectapply() {
        self.TF_toast("你的连麦申请被取消")
      
        self.drawing.podiumConfiguration.podiumStatus(.noApply)
    }
   //   #pragma mark 主动下讲台
    public func rtcDown(_ model: TalkfunRtcModel) {
        
        self.videoArea.removeFromVideo(model)
        self.drawing.podiumConfiguration.podiumStatus(.noApply)
          
            if (model.isMe) {

            //1.不是1v6  2.已经上讲台
              if(self.smallType != "2" && self.talkfunSDK.rtcManager.allowApply == false){

                  self.drawing.podiumConfiguration.onPodium.isHidden = true

               }
                self.TF_toast("你已取消连麦")
                self.navigationBar.takeThePodium(true, liveStart: true, modetype: self.modetype, smallType: self.smallType, shipinType: "0")
                self.navigationBar.ondium.onPodium(.noApply)
           
            if (self.modetype == "6")
            {
                self.videoArea.videoSessionsArray.removeAllObjects()
         
            if (self.talkfunSDK.realDesktop == false) {
               self.cameraView.isHidden = false
            }

                self.isShowvCameraView(true)

            }

         }

    }
    //#pragma mark 踢下讲台
    public func rtcKick(_ model: TalkfunRtcModel) {
   
        self.rtcDown(model)
    
    }
   // #pragma mark 用户离线
    public func rtcOffline(_ model: TalkfunRtcModel) {
 
        self.videoArea.removeFromVideo(model)
    }
  //  #pragma mark 打开摄像头
    public func rtcOpenVideo(_ model: TalkfunRtcModel) {
   

        if (model.isFull) {
            self.fullView.view.isHidden = true
            self.fullView.backgroundColor = UIColor.clear
       
            self.fullView.insertSubview(model.view, at: 0)
            
           
            
        } else {
            self.fullView.view.isHidden = true
        }

        self.videoArea.updateModel(model)
        if (model.isMe) {

            self.TF_toast("你可以使用摄像头了")
            TalkfunSettingToolsManager.shared().setZhuboCloseVideoStatus(false, xid: self.talkfunSDK.xid)
         
            self.setButtonView.hiddenBtn(true)

            self.navigationBar.updateModel(model)

    }

    }
    //#pragma mark 关闭摄像头
    public func rtcCloseVideo(_ model: TalkfunRtcModel) {

        if (model.isFull) {
            self.fullView.view.isHidden = false
            self.fullView.backgroundColor = UIColor.clear
        } else {
            self.fullView.view.isHidden = true
        }
        self.videoArea.updateModel(model)
       if (model.isMe) {
        self.TF_toast("你的摄像头已关闭")

        TalkfunSettingToolsManager.shared().setZhuboCloseVideoStatus(true, xid: self.talkfunSDK.xid)
     
        self.setButtonView.hiddenBtn(false)
        self.navigationBar.updateModel(model)

    }

    }
   // #pragma mark 打开麦克风
    public func rtcOpenAudio(_ model: TalkfunRtcModel) {
    
        self.videoArea.updateModel(model)

        if (model.isMe) {
            self.TF_toast("你的麦克风已开启")
           
            self.navigationBar.updateModel(model)
            
            TalkfunSettingToolsManager.shared().setZhuboCloseAudioStatus(false, xid: self.talkfunSDK.xid)
          
            let switches = self.setButtonView.swicthArr[4] as! TFSwitch
             switches.isOn = true
        }
    }
    //#pragma mark 关闭麦克风
    public func rtcCloseAudio(_ model: TalkfunRtcModel)
    {
   
        self.videoArea.updateModel(model)
       if (model.isMe) {
           self.TF_toast("你的麦克风已关闭")
       
           TalkfunSettingToolsManager.shared().setZhuboCloseAudioStatus(true, xid: self.talkfunSDK.xid)
           self.navigationBar.updateModel(model)
   
           let switches = self.setButtonView.swicthArr[4] as! TFSwitch
           switches.isOn = false

     }
    }
   // #pragma mark  打开涂鸦权限
    public func rtcDrawEnable(_ model: TalkfunRtcModel)
    {
        self.drawPower = true
        model.drawPower = true
        self.videoArea.updateModel(model)

             if (model.isMe)
             {
                 self.TF_toast("你已被授予涂鸦权限")
                
                 self.drawing.whiteboardTools.isHidden = false
             }else{
             //本来有涂鸦权限,现在切换给别人了
             if(self.drawing.whiteboardTools.isHidden==false){
                 self.TF_toast("你的涂鸦权限已被收回")
              
             //不是自己就隐藏
                 self.drawing.whiteboardTools.isHidden = true
             }
             }


    }
    //#pragma mark  关闭涂鸦权限
    public func rtcDrawDisable(_ model: TalkfunRtcModel)
    {
        self.drawPower = false
        self.videoArea.updateModel(model)
        if (model.isMe) {
            self.TF_toast("你的涂鸦权限已被收回")
            self.drawing.whiteboardTools.isHidden = true
        }

    }
   // #pragma mark  奖励
    public func rtcAward(_ model: TalkfunRtcModel) {
        self.videoArea.updateModel(model)

        let chatData = TF1to16LiveChatData()
        chatData.nickname = model.nickname
        chatData.score = model.score
        chatData.isAward = true
        self.chatArea.setAwardModel(chatData)
        if (model.isMe) {
            self.awardView.rotateView()
        }
    }
     public override var supportedInterfaceOrientations: UIInterfaceOrientationMask{

         return .landscapeRight
     }
     
     public override var shouldAutorotate: Bool{
         return false
     }
     public override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
         return .landscapeRight
     }

     ////隐藏状态栏
     public override var prefersStatusBarHidden: Bool
     {
         return true
     }
    deinit {
            print("大班互动没有强引用===")
        }

}
